package com.ledim.fragment;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.PersonalActivity;
import com.ledim.bean.FocusDataBean;
import com.ledim.bean.LedimUserBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.bean.base.BaseResultInfo;
import com.ledim.fragment.base.LedimBaseDialogFragment;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.DensityUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.letv.android.young.client.R;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ccx on 16/9/27.
 * 用户信息的Fragment可以添加关注，用于聊天页面,可禁言可踢出
 */
public class LedimUserFragment extends LedimBaseDialogFragment {

    private LedimUserBean mUser;
    private ImageView iv_follow_state, iv_forbid_logo, iv_forbid_speak, iv_kick_off;
    private int mRelation;
    private boolean mMeIsRoomCreater;//房主拥有禁言和踢出权限
    private View ll_creater_right;
    private String mRoomId;

    public static LedimUserFragment getInstance(LedimUserBean user, boolean isRoomCreater,
                                                String roomId) {
        LedimUserFragment fragment = new LedimUserFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ConstantUtil.DATA, user);
        bundle.putString(ConstantUtil.ID, roomId);
        bundle.putBoolean(ConstantUtil.ROOM_CREATER, isRoomCreater);
        fragment.setArguments(bundle);
        return fragment;
    }

    @SuppressLint("ValidFragment")
    private LedimUserFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.dialog_bottom);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mUser = (LedimUserBean) bundle.getSerializable(ConstantUtil.DATA);
            mMeIsRoomCreater = bundle.getBoolean(ConstantUtil.ROOM_CREATER);
            mRoomId = bundle.getString(ConstantUtil.ID);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_follow_state:
                doFollowAction();
                break;
            case R.id.iv_user_photo:
                PersonalActivity.jumpPersonalHomePage(getContext(), mUser.userId);
                dismiss();
                break;
            case R.id.iv_forbid_speak:
                //禁言或者解除禁言
                modifyChatUserState(mRoomId, mUser.userId,
                        mUser.silent == 1 ? ConstantUtil.ChatUserActionConstant.UNFORBID_SPEAK
                                          : ConstantUtil.ChatUserActionConstant.FORBID_SPEAK);
                break;
            case R.id.iv_kick_off:
                // 踢出
                modifyChatUserState(mRoomId, mUser.userId, ConstantUtil.ChatUserActionConstant.KICK_OFF);
                break;
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_user_info;
    }

    @Override
    public void initView(View view) {
        iv_follow_state = (ImageView) view.findViewById(R.id.iv_follow_state);
        ImageView iv_user_state = (ImageView) view.findViewById(R.id.iv_user_state);
        iv_follow_state.setOnClickListener(this);
        SimpleDraweeView iv_user_photo = (SimpleDraweeView) view.findViewById(R.id.iv_user_photo);
        iv_user_photo.setOnClickListener(this);
        TextView tv_coin_counts = (TextView) view.findViewById(R.id.tv_coin_counts);
        TextView tv_user_name = (TextView) view.findViewById(R.id.tv_user_name);
        iv_user_state.setImageResource(LedimFunctionUtils.getUserTypeIcon(mUser.status));
        if (mUser.avatar != null && !TextUtils.isEmpty(mUser.avatar.thumb)) {
            FrescoUtil.loadUrl(mUser.avatar.thumb, iv_user_photo);
        }
        ll_creater_right = view.findViewById(R.id.ll_creater_right);
        iv_forbid_logo = (ImageView) view.findViewById(R.id.iv_forbid_logo);
        if (mMeIsRoomCreater) {
            ll_creater_right.setVisibility(View.VISIBLE);
            iv_forbid_speak = (ImageView) view.findViewById(R.id.iv_forbid_speak);
            iv_kick_off = (ImageView) view.findViewById(R.id.iv_kick_off);
            iv_forbid_speak.setOnClickListener(this);
            iv_kick_off.setOnClickListener(this);
            initChatUserSateView();
        } else {
            ll_creater_right.setVisibility(View.INVISIBLE);
        }
        tv_coin_counts.setText(mUser.coin);
        tv_user_name.setText(mUser.nickname);
        setFocusBgByState(mUser.relation);
    }

    @Override
    public void initLayoutParams(WindowManager.LayoutParams wlp) {
        wlp.gravity = Gravity.CENTER;
        wlp.height = DensityUtil.dip2px(getActivity(), 240);
        wlp.width = DensityUtil.dip2px(getActivity(), 270);
    }

    /**
     * 根据状态刷新背景
     */
    private void setFocusBgByState(int focusState) {
        switch (focusState) {
            case ConstantUtil.NOT_FOCUS_STATE:
                iv_follow_state.setImageResource(R.drawable.user_no_follow);
                break;
            case ConstantUtil.ALREADY_FOCUS_STATE:
                iv_follow_state.setImageResource(R.drawable.user_followed_only);
                break;
            case ConstantUtil.TOGETHER_FOCUS_STATE:
                iv_follow_state.setImageResource(R.drawable.user_follow_eachother);
                break;
        }

    }

    /**
     * @param roomId
     * @param uid
     * @param action
     *         禁言 解禁 踢出操作
     */
    private void modifyChatUserState(final String roomId, final String uid, final int action) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .modifyUserChatState(roomId, uid, action)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new Observer<BaseResultInfo>() {
                                  @Override
                                  public void onCompleted() {

                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      ToastUtil.toast("系统错误，请稍后重试");
                                  }

                                  @Override
                                  public void onNext(BaseResultInfo baseResultInfo) {
                                      if (baseResultInfo.success) {
                                          ToastUtil.toast("操作成功");
                                          switch (action) {
                                              case ConstantUtil.ChatUserActionConstant.KICK_OFF:
                                                  mUser.kick = 1;
                                                  break;
                                              case ConstantUtil.ChatUserActionConstant.FORBID_SPEAK:
                                                  mUser.silent = 1;
                                                  break;
                                              case ConstantUtil.ChatUserActionConstant.UNFORBID_SPEAK:
                                                  mUser.silent = 0;
                                                  break;
                                          }
                                          initChatUserSateView();
                                      }
                                  }
                              });
    }

    /**
     * 初始化踢出禁言View
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void initChatUserSateView() {

        if (mUser.kick == 1) {
            iv_kick_off.setClickable(false);
            iv_kick_off.setAlpha(0.5f);
            iv_forbid_speak.setClickable(false);
            iv_forbid_speak.setAlpha(0.5f);
        } else {
            iv_kick_off.setClickable(true);
        }
        if (mUser.silent == 1) {
            iv_forbid_logo.setVisibility(View.VISIBLE);
            iv_forbid_speak.setImageResource(R.drawable.unforbid_speak);
        } else {
            iv_forbid_logo.setVisibility(View.GONE);
            iv_forbid_speak.setImageResource(R.drawable.forbid_speak);
        }

    }

    public void doFollowAction() {
        LedimHttpObserver observer = new LedimHttpObserver<BaseResultDataInfo<FocusDataBean>>() {
            @Override
            public void onCompleted() {
                super.onCompleted();
            }

            @Override
            public void onNext(BaseResultDataInfo<FocusDataBean> data) {
                super.onNext(data);
                if (data != null) {
                    if (data.success) {
                        //成功
                        mUser.relation = data.data.type;
                        setFocusBgByState(mUser.relation);
                    } else {
                        //失败
                        LedimApiServiceUtils.followFailMsg(mUser.relation);
                    }

                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                LogUtil.e(e.getMessage());
                LedimApiServiceUtils.followFailMsg(mUser.relation);
            }
        };
        switch (mUser.relation) {
            case ConstantUtil.NOT_FOCUS_STATE:
                LedimApiServiceUtils.requestFanAndFollowData(ConstantUtil.NOT_FOCUS_STATE, mUser.userId, observer);
                break;
            case ConstantUtil.ALREADY_FOCUS_STATE:
            case ConstantUtil.TOGETHER_FOCUS_STATE:
                LedimApiServiceUtils.requestFanAndFollowData(ConstantUtil.ALREADY_FOCUS_STATE, mUser.userId, observer);
                break;
        }

    }
}
